package com.yuebook.base.common.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

/**
 * @author honglei
 * @date 2018/10/26 下午10:01
 */
@Slf4j
public class Propertyutils {

    private static final Logger logger = LoggerFactory.getLogger(Propertyutils.class);

    private static ConcurrentHashMap<String, String> map;

    private static void ensureProp(){
        if (map == null) {
            logger.info("properties loading............");
            map = new ConcurrentHashMap<String, String>();
            //根据classpath获取resource
            PathMatchingResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
            Properties props = new Properties();
            try {
                Resource[] locations = resourceResolver.getResources("classpath*:*.properties");
                for (Resource resource : locations) {
                    InputStream in = resource.getInputStream();
                    props.load(in);
                    for (Entry<Object, Object> en : props.entrySet()) {
                        String key = en.getKey().toString();
                        String value = en.getValue().toString();
                        logger.info(key+"="+value);
                        map.put(key, value);
                    }
                }

            } catch (IOException e) {
                logger.warn("", e);
            }
        }
    }

    public static String getProperty(String key) {
        ensureProp();
        return map.get(key);
    }

}
